import Interface
import Display
import Data

import requests
import tkinter as tk

searchUrl = Data.baseUrl + "/search"
checkUrl = Data.baseUrl + "/check/music?id="


def createFrame():
    # 生成容器
    global mainSearchFrame
    mainSearchFrame = tk.Frame(Interface.app, borderwidth=1, relief="raised")
    mainSearchFrame.pack(side='left', fill='both')
    tk.Label(mainSearchFrame, text="搜索").pack(side='top', anchor="w", fill="both")

    # 生成容器
    searchFrame = tk.Frame(mainSearchFrame)
    searchFrame.pack(side='top')
    global text
    text = tk.Entry(searchFrame)
    text.pack(side='left')
    text.bind('<FocusIn>', lambda event: text.delete('0', 'end'))
    tk.Button(searchFrame, text="查询", command=lambda: search(text.get())).pack(side='left')
    Interface.app.bind("<Return>", lambda event: search(text.get()))  # 按钮绑定回车键
    tk.Button(mainSearchFrame, text="选中此板块以使用滚轮", command=lambda type="search": Display.freshScro(type)).pack(side='top', anchor="w")

    # 创建画布和滚动条，Canvas,Scrollbar放置在主窗口上
    global searchCanvas
    searchCanvas = tk.Canvas(master=mainSearchFrame)
    searchCanvas.pack(side='left', fill='both', expand=True)
    global searchScro
    searchScro = tk.Scrollbar(master=mainSearchFrame)
    searchScro.pack(side='right', fill='y')
    # 将滚动按钮绑定在Canvas上
    searchCanvas.configure(yscrollcommand=searchScro.set, scrollregion=searchCanvas.bbox("all"))
    searchScro.config(command=searchCanvas.yview)


def search(word):
    # 获取数据
    searchWordUrl = searchUrl + "?keywords=" + word
    headers = {"Accept": "application/vnd.github.v3+json"}
    data = requests.get(searchWordUrl, headers=headers)
    response_dict = data.json()

    Display.display("search", response_dict.get("result").get("songs"))
